<?php 
/* --------------------------------
 * Функции по работе с экспортом XML
 --------------------------------*/
 
	class xml_generate extends Load_use
	{
		private $file;
		private $utm;
		private $errors = array();
		private $hc = '';
		private $price;
		private $store_products = array();
		private $deliveries = array();
		private $sales_notes = array();
		private $sales_notes_products = array();
		
		public function __construct( $conn ){
			$this->conn = $conn;
		}
		
		
		public function getingXml( $avtomatical )
		{
			global $xml_prices, $COST_OF_DELIVERY_1;
			$this->deliveries = $COST_OF_DELIVERY_1;
			
			/* $this->deliveries = array( 0 , 600 , 350 , 300 , 800 , 1000 ); */
			$this->getXmlData();
			
			foreach( $xml_prices as $this->utm => $this->price )
			{
				if( $this->price['avaliable'] )
				{
					if( $avtomatical && $this->price['file'] != 'ym_price.xml' )
						continue;
					
					
					if( $this->file = @fopen( PATH_TO_INC_DIR.'/'.$this->price['file'] , 'wb' ))
					{
						$this->exportAllCategories(); 	// Шапка. И категории
						$this->exportProducts(); 		// Товары. И футер
						fclose( $this->file );
					}
					else{
						$this->errors[] = getcwd();
						$this->errors[] = 'ОШИБКА ПРИ ОТКРЫТИИ ПРАЙСА '.PATH_TO_INC_DIR.'/'.$this->price['file'];
					}
				}
			}
			return '<span class="red_str">'.implode( '<br/>', $this->errors ).'</span>';
		}
		
		function getXmlData()
		{
			$this->conn->query('SELECT id, type, value FROM `store_product_xml_data` WHERE type = "sales_notes"');
			while( $row = $this->conn->fetch() )
					$this->sales_notes[$row->id] = $row->value;

			$this->conn->query('SELECT xml_data_id, product_code FROM `store_product_xml_data_relation`');
			while( $row = $this->conn->fetch() )
				$this->sales_notes_products[$row->product_code] = $row->xml_data_id;
		}
		 
		function exportAllCategories()
		{
			if( !$this->hc ) 
			{
				$this->hc .= "<?xml version=\"1.0\" encoding=\"windows-1251\"?>\n";
				$this->hc .= "	<!DOCTYPE yml_catalog SYSTEM \"shops.dtd\">\n";
				$this->hc .= "		<yml_catalog date=\"".date("Y-m-d H:i")."\">\n";
				$this->hc .= "			<shop>\n";
				$this->hc .= "				<name>".SITE_NAME."</name>\n";
				$this->hc .= "				<company>".SITE_NAME."</company>\n";
				$this->hc .= "				<url>".HOST_NAME."</url>\n";
				$this->hc .= "				<currencies>\n";
				$this->hc .= "					<currency id=\"RUR\" rate=\"1\" plus=\"1\"/>\n";
				$this->hc .= "				</currencies>\n";
				$this->hc .= "				<categories>\n";
				
				$this->conn->query('SELECT id, title, parents, templ FROM pages WHERE templ IN( "category", "sub_category" )');
				while ( $cat = $this->conn->fetch() )
				{
					$parentId = ( $cat->templ == 'sub_category' ) ? ' parentId="'.array_pop( getIdsArr( $cat->parents ) ).'"' : '';
					$this->hc .= "					<category id=\"".$cat->id."\"".$parentId.">".myIconv( $cat->title )."</category>\n";
				}
				$this->hc .= "				</categories>\n";				
			}
			fputs( $this->file, $this->hc );
		}
		
		private function exportProducts()  // Вытаскиваем товары и записываем в xml файл
		{
 			if( empty( $this->store_products[$this->price['where']] ) )	{
				$products = getProductList( array( 'where' => '`pp` IN( 1, 3, 4, 5 ) AND  `price_retail` > 0 AND '.$this->price['where'] ) );
				$this->store_products[$this->price['where']] = $products['list'];
			}
			
			$names = array();
			$p = "				<offers>\n";
			
			foreach( $this->store_products[$this->price['where']] as $pr )
			{
				$err = array();

				if( in_array( $pr->name, $names ) )
					$err[] = 'Код товара '.$pr->product_code.'. Данный товар дублируется по названию "'.$pr->name.'"';

				$names[] = $pr->name;
				
				if( !$pr->brand )
					$err[] = 'Код товара '.$pr->product_code.'. Не указан производитель';
				
				$img_path = '/inc/images/products/'.$pr->product_code.'.jpg';
				$img = file_exists( HOME_PATH.$img_path ) ? HOST_NAME.$img_path : '';
 				if( !$img )
					$err[] = 'Код товара '.$pr->product_code.'. Отсутствует картинка';
				
				if( !strlen( $pr->volume ) || !isset( $this->deliveries[$pr->volume] ) )
					$err[] = 'Код товара '.$pr->product_code.'. Не указана габаритность';
					
				if( count( $err ) ) {
					$this->errors[$pr->product_code] = implode( '<br/>', $err );
					continue;
				}
					
				$vendor_model	= $this->price['vendor_model']	? ' type="vendor.model"'	: '';
				$bid	= $pr->bid			? ' bid="'.$pr->bid.'"'		: '';
				$cbid	= $pr->cbid	== 30	? ' cbid="'.$pr->cbid.'"'	: '';
				

				$prefix			= $this->replaceIllegalChars( myIconv( $pr->prefix ) );
				$vendor			= $this->replaceIllegalChars( myIconv( $pr->brand ) );
				$name			= $this->replaceIllegalChars( myIconv( $pr->name ) );
				$full_name		= $pr->market_name ? $this->replaceIllegalChars(  myIconv( $pr->market_name ) ) : $prefix." ".$vendor." ".$name;
				// $full_name		= $this->replaceIllegalChars( myIconv( $pr->market_name ? $pr->market_name : $pr->prefix." ".$pr->brand." ".$pr->name ) );
				$sales_notes	= $this->replaceIllegalChars( myIconv( isset( $this->sales_notes_products[$pr->product_code] ) ? ( isset( $this->sales_notes[$this->sales_notes_products[$pr->product_code]] ) ? $this->sales_notes[$this->sales_notes_products[$pr->product_code]] : '' ) : '' ) );
			
				
				$p .= "					<offer id=\"".$pr->product_code."\"".$vendor_model.$bid.$cbid." available=\"".( $pr->pp == 1 ? 'true' : 'false' )."\">\n";
				$p .= "						<url>".HOST_NAME.'/'.$pr->url."?from=".$this->utm."</url>\n";
				$p .= "						<price>".(int)$pr->price_retail."</price>\n";
				$p .= "						<currencyId>RUR</currencyId>\n";
				$p .= "						<categoryId>".array_pop( getIdsArr( $pr->parents ) )."</categoryId>\n";
				$p .= "						<picture>".$img."</picture>\n";
				$p .= "						<local_delivery_cost>".$this->deliveries[$pr->volume]."</local_delivery_cost>\n";
 			if( $this->price['vendor_model'] )
			{
				$p .= "						<typePrefix>".$prefix."</typePrefix>\n";
				$p .= "						<vendor>".$vendor."</vendor>\n";
				$p .= "						<model>".$name."</model>\n";
			}
			else
			{
				$p .= "						<name>".$full_name."</name>\n";
 			}
if($sales_notes)$p .= "						<sales_notes>".$sales_notes."</sales_notes>\n";
				$p .= "						<manufacturer_warranty>true</manufacturer_warranty>\n";
				$p .= "					</offer>\n";
			}
			$p .= "				</offers>\n";
			$p .= "			</shop>\n";
			$p .= "		</yml_catalog>\n";
			
			fputs( $this->file, $p );
		}
		
		private function replaceIllegalChars( $str )
		{
			$healthy = array( '"',		'&',	'>',		'<',	"'" );
			$yummy   = array( '&quot;',	'&amp;', '&gt;',	'&lt;', '&apos;');
			return str_replace( $healthy, $yummy, $str );
		}
	}